package com.vertx.discovery;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.consul.*;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

import java.util.Arrays;

public class DiscoveryVerticle extends AbstractVerticle {


	public static void main(String[] args) {

		Runner.runExample(DiscoveryVerticle.class);

	}


	@Override
	public void start(Promise<Void> startPromise) throws Exception {


		Router router = Router.router(vertx);
		router.route().handler(BodyHandler.create());
		router.get("/service/:serviceName").handler(this::getService);

		vertx.createHttpServer().requestHandler(router).listen(8888);

		ConsulClient consulClient = ConsulClient.create(vertx);
		ServiceOptions opts = new ServiceOptions()
				.setName("testService1")
				.setId("testService111")
				.setTags(Arrays.asList("tag1", "tag2"))
				.setCheckOptions(new CheckOptions().setTtl("10s"))
				.setAddress("127.0.0.1")
				.setPort(8080);

		consulClient.registerService(opts, res -> {
			if (res.succeeded()) {
				System.out.println("Service successfully registered");
			} else {
				res.cause().printStackTrace();
			}

		});


	}

	private void getService(RoutingContext context) {
		String serviceName = context.request().getParam("serviceName");

		ConsulClient consulClient = ConsulClient.create(vertx);

		consulClient.catalogServiceNodes(serviceName, res -> {
			if (res.succeeded()) {
				System.out.println("found " + res.result().getList().size() + " services");
				System.out.println("consul state index: " + res.result().getIndex());
				for (Service service : res.result().getList()) {
					System.out.println("Service node: " + service.getNode());
					System.out.println("Service address: " + service.getAddress());
					System.out.println("Service port: " + service.getPort());
				}
			} else {
				res.cause().printStackTrace();
			}
		});
	}

}